package com.supermap.business.cloud.push;


import com.alibaba.dubbo.config.annotation.Reference;
import com.supermap.dubbo.api.cloud.push.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author aqua
 * @description
 * @date 2018年11月30 上午 9:36
 * @email 1301584033@qq.com
 */
@ServerEndpoint(value = "/websocket/{sid}/{productId}")
@Component
public class MyWebSocket {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String  sid=null;
    private String productId=null;

    //此处是解决无法注入的关键
    private static ApplicationContext applicationContext;
    //你要注入的service或者dao
    @Reference(timeout = 1000)
    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyWebSocket.applicationContext = applicationContext;
    }
    private PushController pushController;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam("sid")String sid,@PathParam("productId")String productId, Session session) {
        this.session = session;
        this.sid=sid;
        this.productId=productId;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            sendTopicMessage();
        } catch (Exception e) {
            System.out.println("websocket IO异常");

        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }


    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        for (MyWebSocket item : webSocketSet) {
            //指定推送
            if(item.sid.equals(sid)){
                item.sendMessage(message);
            }

        }
    }



    /**
     * 调用消息推送方法
     * */
     public void sendMessage(String message)  {
         try {
             this.session.getBasicRemote().sendText(message);
         }catch (Exception e){

         }

     }

     /**
      * 指定推送
      * */
    public static void sendInfo(String message,String cid)  {
        for (MyWebSocket item : webSocketSet) {
                //指定推送
                 if(item.sid.equals(cid)){
                    item.sendMessage(message);
                   }

        }

    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }


    //广播推送消息

    public void sendTopicMessage() {
        pushController = applicationContext.getBean(PushController.class);
        for (MyWebSocket item : webSocketSet) {
            //指定推送
            if(item.sid.equals(sid)){
                if(productId==null){
                    //默认全国APP项目
                    productId="quanguoapp2019131xsadwqeq";
                }
                item.sendMessage(pushController.getReceiveuserIdCount(sid,productId).getJsonStr());
            }

        }

    }

}
